<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import request, { SERVER_BASE_URL } from '@/utils/request';
import { ElMessage, ElInputNumber } from 'element-plus';
import { ArrowLeftBold, ArrowRightBold, Star, StarFilled } from "@element-plus/icons-vue"
import { useUserStore } from '@/stores/user'; // 假设存在用户状态管理

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const commodity = ref(null);
const loading = ref(true);
const currentImageIndex = ref(0);
const quantity = ref(1);
const addingToCart = ref(false);
const favoriteLoading = ref(false);
const isFavorite = ref(false);

// 获取商品详情
const fetchCommodityDetail = async () => {
  loading.value = true;
  try {
    const id = route.params.id;
    const response = await request.get(`/commodities/${id}`);
    commodity.value = response;
    loading.value = false;
    
    // 获取商品详情后检查是否已收藏
    checkFavoriteStatus();
  } catch (error) {
    ElMessage.error('获取商品详情失败');
    console.error(error);
    loading.value = false;
  }
};

// 检查当前商品是否已被用户收藏
const checkFavoriteStatus = async () => {
  const userData = JSON.parse(localStorage.getItem('user'));
  if (!userData || !commodity.value) return;
  
  try {
    favoriteLoading.value = true;
    const res = await request.get('/favorites/check', {
      params: {
        userId: userData.id,
        commodityId: commodity.value.id
      }
    });
    
    if (res.code === 200) {
      isFavorite.value = res.data.isFavorite;
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error);
  } finally {
    favoriteLoading.value = false;
  }
};

// 添加或取消收藏
const toggleFavorite = async () => {
  const userData = JSON.parse(localStorage.getItem('user'));
  
  if (!userData) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  
  if (!commodity.value) return;
  
  try {
    favoriteLoading.value = true;
    
    if (isFavorite.value) {
      // 已收藏，执行取消收藏
      const res = await request.delete('/favorites/remove', {
        params: {
          userId: userData.id,
          commodityId: commodity.value.id
        }
      });
      
      if (res.code === 200) {
        isFavorite.value = false;
        ElMessage.success('已取消收藏');
      } else {
        ElMessage.error(res.message || '取消收藏失败');
      }
    } else {
      // 未收藏，执行添加收藏
      const res = await request.post('/favorites/add', {
        userId: userData.id,
        commodityId: commodity.value.id
      });
      
      if (res.code === 200) {
        isFavorite.value = true;
        ElMessage.success('收藏成功');
      } else {
        ElMessage.error(res.message || '收藏失败');
      }
    }
  } catch (error) {
    console.error('操作收藏失败:', error);
    ElMessage.error('操作失败，请稍后重试');
  } finally {
    favoriteLoading.value = false;
  }
};

// 处理图片URL
const getImageUrl = (url) => {
  if (!url) return '';

  // 确保有服务器地址前缀
  let fullUrl = url;
  if (url.startsWith('/uploads/')) {
    fullUrl = SERVER_BASE_URL + url;
  }

  return fullUrl;
};

// 切换显示图片
const changeImage = (index) => {
  currentImageIndex.value = index;
};

// 向前切换图片
const prevImage = () => {
  if (!commodity.value || !commodity.value.image || commodity.value.image.length <= 1) return;
  
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--;
  } else {
    // 循环到最后一张
    currentImageIndex.value = commodity.value.image.length - 1;
  }
};

// 向后切换图片
const nextImage = () => {
  if (!commodity.value || !commodity.value.image || commodity.value.image.length <= 1) return;
  
  if (currentImageIndex.value < commodity.value.image.length - 1) {
    currentImageIndex.value++;
  } else {
    // 循环到第一张
    currentImageIndex.value = 0;
  }
};

// 添加到购物车
const addToCart = async () => {
  if (!commodity.value) return;
  
  // 检查用户是否登录
  const userData = JSON.parse(localStorage.getItem('user'));
  
  if (!userData) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  
  try {
    addingToCart.value = true;
    const cartItem = {
      userId: userData.id,
      commodityId: commodity.value.id,
      quantity: quantity.value,
      selected: true
    };
    
    const response = await request.post('/cart/add', cartItem);
    
    if (response.code === 200) {
      ElMessage.success('添加到购物车成功');
    } else {
      ElMessage.error(response.message || '添加到购物车失败');
    }
  } catch (error) {
    console.error('添加到购物车失败:', error);
    ElMessage.error('添加到购物车失败');
  } finally {
    addingToCart.value = false;
  }
};

// 立即购买
const buyNow = () => {
  if (!commodity.value) return;
  
  // 检查用户是否登录
  const userData = JSON.parse(localStorage.getItem('user'));
  
  if (!userData) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  
  // 创建结算项目并存储到localStorage
  const checkoutItem = {
    id: Date.now(), // 临时ID
    userId: userData.id,
    commodityId: commodity.value.id,
    commodity: commodity.value,
    quantity: quantity.value,
    selected: true
  };
  
  // 将商品信息保存到localStorage
  localStorage.setItem('checkoutItems', JSON.stringify([checkoutItem]));
  
  // 跳转到结算页面
  router.push('/checkout');
};

onMounted(() => {
  fetchCommodityDetail();
});
</script>

<template>
  <div class="commodity-detail-container">
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else-if="commodity" class="commodity-detail">
      <div class="detail-left">
        <!-- 主图 -->
        <div class="main-image">
          <el-image
            v-if="commodity.image && commodity.image.length > 0"
            :src="getImageUrl(commodity.image[currentImageIndex])"
            fit="contain"
          >
            <template #error>
              <div class="image-placeholder">暂无图片</div>
            </template>
          </el-image>
          <div v-else class="image-placeholder">暂无图片</div>
          
          <!-- 左右箭头导航 -->
          <div 
            v-if="commodity.image && commodity.image.length > 1" 
            class="image-nav prev"
            @click.stop="prevImage"
          >
            <el-icon><ArrowLeftBold /></el-icon>
          </div>
          
          <div 
            v-if="commodity.image && commodity.image.length > 1" 
            class="image-nav next"
            @click.stop="nextImage"
          >
            <el-icon><ArrowRightBold /></el-icon>
          </div>
          
          <!-- 图片指示器 -->
          <div 
            v-if="commodity.image && commodity.image.length > 1" 
            class="image-indicators"
          >
            <span 
              v-for="(img, index) in commodity.image" 
              :key="index"
              :class="{ active: currentImageIndex === index }"
              @click="changeImage(index)"
            ></span>
          </div>
        </div>
        
        <!-- 缩略图列表 -->
        <div class="thumbnail-list" v-if="commodity.image && commodity.image.length > 1">
          <div
            v-for="(img, index) in commodity.image"
            :key="index"
            class="thumbnail-item"
            :class="{ active: currentImageIndex === index }"
            @click="changeImage(index)"
          >
            <el-image
              :src="getImageUrl(img)"
              fit="cover"
            />
          </div>
        </div>
      </div>
      
      <div class="detail-right">

        <div class="favorite-status" v-if="isFavorite">
          <el-tag type="warning" effect="light">
            <el-icon><StarFilled /></el-icon>
            <span style="margin-left: 5px;">已收藏</span>
          </el-tag>
        </div>

        <h1 class="commodity-name">{{ commodity.name }}</h1>

        <div class="price-container">
          <span class="price-label">价格:</span>
          <span class="price-value">¥{{ commodity.price }}</span>
        </div>
        
        <div class="info-item">
          <span class="info-label">销量:</span>
          <span class="info-value">{{ commodity.salesVolume || 0 }}</span>
        </div>
        
        <div class="info-item">
          <span class="info-label">库存:</span>
          <span class="info-value">{{ commodity.stock || 0 }}</span>
        </div>
        
        <div class="info-item" v-if="commodity.categoryTag && commodity.categoryTag.length">
          <span class="info-label">分类:</span>
          <div class="tag-list">
            <el-tag 
              v-for="tag in commodity.categoryTag" 
              :key="tag" 
              type="info" 
              effect="plain" 
              size="small"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
        
        <div class="quantity-container">
          <span class="info-label">数量:</span>
          <el-input-number 
            v-model="quantity" 
            :min="1" 
            :max="commodity.stock || 999" 
            size="default"
          />
        </div>
        
        <div class="action-container">
          <el-button 
            type="primary" 
            size="large"
            :disabled="!commodity.stock || addingToCart" 
            :loading="addingToCart"
            @click="addToCart"
          >
            {{ addingToCart ? '正在添加...' : '加入购物车' }}
          </el-button>
          
          <el-button 
            type="danger" 
            size="large"
            style="width: 200px"
            :disabled="!commodity.stock" 
            @click="buyNow"
          >
            立即购买
          </el-button>
          
          <el-button
            type="default"
            size="large"
            :icon="isFavorite ? StarFilled : Star"
            circle
            :loading="favoriteLoading"
            @click="toggleFavorite"
            style="color: #ffd100;font-size: 30px"
          />
        </div>
      </div>
    </div>
    
    <div v-else class="empty-container">
      <el-empty description="商品不存在或已下架" />
    </div>
  </div>
</template>

<style scoped>
.commodity-detail-container {
  padding: 30px;
  border-radius: 0;
  box-shadow: none;
  max-width: 100%;
  margin: 0 auto;
  background-image: url('@/assets/bg.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: repeat;
}

.loading-container {
  padding: 20px;
}

.commodity-detail {
  display: flex;
  gap: 30px;
}

@media (max-width: 768px) {
  .commodity-detail {
    flex-direction: column;
  }
  
  .commodity-detail-container {
    padding: 15px;
  }
}

.detail-left {
  flex: 1;
  min-width: 300px;
}

.detail-right {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  flex: 1;
  min-width: 300px;
  max-height: 460px;
  padding: 20px;
}

.main-image {
  width: 100%;
  height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
}

.main-image .el-image {
  width: 100%;
  height: 100%;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 16px;
  background-color: #f5f7fa;
}

.thumbnail-list {
  display: flex;
  margin-top: 10px;
  gap: 10px;
  overflow-x: auto;
  padding-bottom: 5px;
}

.thumbnail-item {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  cursor: pointer;
  border: 2px solid transparent;
  overflow: hidden;
}

.thumbnail-item.active {
  border-color: #409EFF;
}

.thumbnail-item .el-image {
  width: 100%;
  height: 100%;
}

.commodity-name {
  font-size: 24px;
  font-weight: 500;
  margin: 0 0 20px 0;
  color: #303133;
}

.price-container {
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #EBEEF5;
}

.price-label {
  font-size: 16px;
  color: #606266;
}

.price-value {
  font-size: 28px;
  color: #ff6700;
  font-weight: bold;
  margin-left: 10px;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-label {
  font-size: 16px;
  color: #606266;
  width: 60px;
}

.info-value {
  font-size: 16px;
  color: #303133;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;

  gap: 10px;
}

.quantity-container {
  margin: 20px 0;
  display: flex;
  align-items: center;
}

.action-container {
  margin-top: 50px;
  display: flex;
  gap: 15px;
}

.favorite-status {
  margin-top: 5px;
  float: right;
}

.empty-container {
  padding: 50px 0;
  text-align: center;
}

/* 图片导航箭头 */
.image-nav {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 40px;
  height: 40px;
  background-color: rgba(0, 0, 0, 0.3);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 50%;
  z-index: 10;
  font-size: 24px;
  transition: all 0.3s;
  opacity: 0;
}

.main-image:hover .image-nav {
  opacity: 1;
}

.image-nav:hover {
  background-color: rgba(0, 0, 0, 0.6);
}

.image-nav.prev {
  left: 10px;
}

.image-nav.next {
  right: 10px;
}

/* 图片指示器样式 */
.image-indicators {
  position: absolute;
  bottom: 15px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
}

.image-indicators span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
  cursor: pointer;
}

.image-indicators span.active {
  background-color: #409EFF;
  width: 10px;
  height: 10px;
}
</style>